import { isNaN } from 'lodash';

// 时分秒转化为数字 - 仅用于比较
export const convertTimeToNumUtil = time => +new Date(`2021/07/26 ${time}`);

const isValidNum = (num, { mode = 'thanZero' } = {}) => {
  if (typeof num === 'undefined') {
    return true;
  }
  let newNum = typeof num === 'string' ? num.trim() : num;
  if (!newNum && typeof newNum !== 'number') {
    return null;
  }
  newNum = +newNum;
  if (mode === 'thanZero') {
    return newNum > 0;
  }

  return !isNaN(newNum);
};

// 获取文件校验结果信息
export const getTaskFileValidInfo = result => {
  if (!(result?.length > 0)) {
    return { errMsg: '文件商品数据为空', isValid: false };
  }
  let errMsg = '';
  let isValidFail = result.some(item => {
    const rowText = `第${item.rowNo}行`;
    if (!item.channelCode) {
      errMsg = `${rowText}渠道编码为空`;
      return true;
    }
    if (!item.goodsCode) {
      errMsg = `${rowText}商品编码为空`;
      return true;
    }
    if (!(item.newChannelPrice || item.limitFrequency || item.limitNum || item.newActivityPrice || item.activityPriceLimit)) {
      errMsg = `${rowText}没有设置调价需求`;
      return true;
    }
    if (!isValidNum(item.newChannelPrice)) {
      errMsg = `${rowText}调原价必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.limitFrequency)) {
      errMsg = `${rowText}限购频率必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.limitNum)) {
      errMsg = `${rowText}限购数量必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.newActivityPrice)) {
      errMsg = `${rowText}调特价必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.activityPriceLimit)) {
      errMsg = `${rowText}特价限购必须为大于0的数字`;
      return true;
    }
    if (!isValidNum(item.costPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}成本价不是数字`;
      return true;
    }
    if (!isValidNum(item.channelPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}商品原价不是数字`;
      return true;
    }
    if (!isValidNum(item.competeChannelPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}竞对原价最低价不是数字`;
      return true;
    }
    if (!isValidNum(item.competeActivityPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}竞对特价最低价不是数字`;
      return true;
    }
    if (!isValidNum(item.competeMaxSales, { mode: 'notNaN' })) {
      errMsg = `${rowText}竞对最高销量不是数字`;
      return true;
    }
    if (!isValidNum(item.cellularSales, { mode: 'notNaN' })) {
      errMsg = `${rowText}蜂窝总销量不是数字`;
      return true;
    }
    if (!isValidNum(item.retailPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}商品原价不是数字`;
      return true;
    }
    if (!isValidNum(item.activityPrice, { mode: 'notNaN' })) {
      errMsg = `${rowText}商品特价不是数字`;
      return true;
    }
    if (!isValidNum(item.salesRank, { mode: 'notNaN' })) {
      errMsg = `${rowText}销售排名不是数字`;
      return true;
    }
    if (!isValidNum(item.monthSales, { mode: 'notNaN' })) {
      errMsg = `${rowText}月售不是数字`;
      return true;
    }
    return false;
  });

  if (!isValidFail) {
    /**
     * 校验是否重复
     */
    const goodsListByChannelCode = result.map(item => `${item.channelCode}-${item.goodsCode}`);
    isValidFail = goodsListByChannelCode.length !== new Set(goodsListByChannelCode).size;
    if (isValidFail) {
      errMsg = '存在重复商品，请核查！';
    }
  }

  return {
    isValid: !isValidFail,
    errMsg,
  };
};

// 获取分时段列表校验结果信息
export const getTaskListValidInfo = tasks => {
  let errMsg = '';

  // 校验表单是否为空
  const isValidNotEmptyFail = tasks.some(task => {
    const rowText = `调价时段第${task.rowIndex}行`;
    if (!task.startTime) {
      errMsg = `${rowText}开始时间不可为空`;
      return true;
    }
    if (!task.endTime) {
      errMsg = `${rowText}结束时间不可为空`;
      return true;
    }
    if (!(task.fileData?.length > 0)) {
      errMsg = `${rowText}请上传商品数据文件`;
      return true;
    }
    return false;
  });

  if (isValidNotEmptyFail) {
    return {
      isValid: false,
      errMsg,
    };
  }

  // 校验是否存在重叠时间段
  const isCrossTimeRange = () => {
    // 按时间排序
    const sortTasks = tasks
      .reduce((prev, curr) => {
        return [
          ...prev,
          {
            rowIndex: curr.rowIndex,
            time: curr.startTimeStamp,
          },
          {
            rowIndex: curr.rowIndex,
            time: curr.endTimeStamp,
          },
        ];
      }, [])
      .sort((x, y) => x.time - y.time);
    // 判断相邻 - index为奇数项时，当前与上一个不属于同一组，或下一个 time 值相同，则判定为重叠
    return sortTasks.some((item, index) =>
      index % 2
        ? item.index !== sortTasks[index - 1].index ||
          (sortTasks[index + 1] && item.time === index % 2
            ? item.index !== sortTasks[index - 1].index ||
              (sortTasks[index + 1] && item.time === index % 2
                ? item.index !== sortTasks[index - 1].index || (sortTasks[index + 1] && item.time === sortTasks[index + 1].time)
                : false,
              [index + 1].time)
            : false,
          [index + 1].time)
        : false,
    );
  };

  if (isCrossTimeRange()) {
    return {
      isVallid: false,
      errMsg: '时间不能重叠',
    };
  }

  const ifFullDay = () => {
    const totalDuration = tasks.reduce((prev, curr) => {
      const duration = curr.endTimeStamp - curr.startTimeStamp + 1000;
      return prev + duration;
    }, 0);
    return totalDuration === 1000 * 60 * 60 * 24;
  };

  if (!ifFullDay()) {
    return {
      isVallid: false,
      errMsg: '请设置24小时完整时间',
    };
  }

  return {
    isValid: true,
    errMsg: '',
  };
};
